from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_x509_certificate

# 加载 CA 证书
with open("ca.crt", "rb") as f:
    ca_cert_pem = f.read()
    ca_cert = load_pem_x509_certificate(ca_cert_pem, default_backend())

# 加载服务器证书
with open("server.crt", "rb") as f:
    server_cert_pem = f.read()
    server_cert = load_pem_x509_certificate(server_cert_pem, default_backend())

# 验证服务器证书是否由 CA 证书签发
try:
    ca_cert.public_key().verify(
        server_cert.signature,
        server_cert.tbs_certificate_bytes,
        padding.PKCS1v15(),
        server_cert.signature_hash_algorithm
    )
    print("服务器证书由 CA 证书签发，验证通过。")
except Exception as e:
    print("服务器证书验证失败:", e)

# 验证证书链
try:
    ca_cert.public_key().verify(
        ca_cert.signature,
        ca_cert.tbs_certificate_bytes,
        padding.PKCS1v15(),
        ca_cert.signature_hash_algorithm
    )
    print("CA 证书自签名验证通过。")
except Exception as e:
    print("CA 证书自签名验证失败:", e)
